package red.mlz.console.controller.category;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import red.mlz.console.annotations.VerifiedUser;
import red.mlz.console.domain.category.CategoryTreeVo;
import red.mlz.module.module.category.entity.Category;
import red.mlz.module.module.category.service.CategoryService;
import red.mlz.module.module.user.entity.User;
import red.mlz.module.utils.BaseUtils;
import red.mlz.module.utils.Response;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @RequestMapping("/category/tree")
    public Response getCategoryTree(@VerifiedUser User loginUser) {
        if (BaseUtils.isEmpty(loginUser)){
            return new Response(1002);
        }
        List<Category> categories = categoryService.findAll();

        // 构建类目树
        List<CategoryTreeVo> categoryTree = buildCategoryTree(categories);

        // 构建响应
        Map<String, Object> result = new HashMap<>();
        result.put("categoryTree", categoryTree);

        return new Response(1001,result);
    }

    // 递归构建类目树
    private List<CategoryTreeVo> buildCategoryTree(List<Category> categories) {
        return categories.stream()
                .filter(c -> c.getParentId() == 0) // 筛选顶级类目
                .map(parent -> {
                    CategoryTreeVo parentVO = new CategoryTreeVo();
                    parentVO.setId(parent.getId());
                    parentVO.setName(parent.getName());
                    parentVO.setImage(parent.getImage());

                    // 递归构建子类目
                    List<CategoryTreeVo> children = buildSubCategories(categories, parent.getId());
                    parentVO.setChildren(children);

                        return parentVO;
                    })
                .collect(Collectors.toList());
    }

    // 递归构建子类目
    private List<CategoryTreeVo> buildSubCategories(List<Category> categories, Long parentId) {
        return categories.stream()
                .filter(c -> parentId != 0 && parentId.equals(c.getParentId()))
                .map(child -> {
                    CategoryTreeVo childVO = new CategoryTreeVo();
                    childVO.setId(child.getId());
                    childVO.setName(child.getName());
                    childVO.setImage(child.getImage());

                    // 递归构建孙类目
                    List<CategoryTreeVo> grandchildren = buildSubCategories(categories, child.getId());
                    childVO.setChildren(grandchildren);

                    return childVO;
                })
                .collect(Collectors.toList());
    }



    @RequestMapping("/category/add")
    public Response addCategory(@VerifiedUser User loginUser,
                                @RequestParam(name = "categoryId",required = false)Long categoryId,
                                @RequestParam(name = "name")String name,
                                @RequestParam(name = "image")String image,
                                @RequestParam(name = "parentId",required = false) Long parentId) {
        if (BaseUtils.isEmpty(loginUser)){
            return new Response(1002);
        }
        try {
            Long resultCategoryId = categoryService.edit(categoryId, name, image, parentId);
            return new Response<>(1001,resultCategoryId.toString());
        }catch (Exception e) {
            return new Response(4004,e.getMessage());
        }
    }

    @RequestMapping ("/category/update")
    public Response updateCategory(@VerifiedUser User loginUser,
                                   @RequestParam(name = "categoryId")Long categoryId,
                                   @RequestParam(name = "name")String name,
                                   @RequestParam(name = "image")String image,
                                   @RequestParam(name = "parentId")Long parentId) {
        if (BaseUtils.isEmpty(loginUser)){
            return new Response(1002);
        }
        try {
            Long resultCategoryId = categoryService.edit(categoryId, name, image, parentId);
            return new Response(1001,resultCategoryId.toString());
        }catch (Exception e) {
            return new Response(4004,e.getMessage());
        }
    }

    @RequestMapping("/category/delete")
    public Response deleteCategory(@VerifiedUser User loginUser,
                                   @RequestParam(name = "categoryId") Long categoryId){
        if (BaseUtils.isEmpty(loginUser)){
            return new Response(1002);
        }

        try {
            if (categoryId != null) {
                // 删除游戏
                Integer isDeleted = categoryService.delete(categoryId);
                if (isDeleted == 0) {
                    return new Response<>(4004,"未找到对应分类，删除失败");
                }
            }else {
                return new Response<>(4004,"请输入有效分类Id");
            }
            return new Response<>(1001,"分类删除成功");
        }catch (Exception e) {
            return new Response(4004,"删除过程中发生错误: " + e.getMessage());
        }
    }


    private List<CategoryTreeVo> convertToTreeVO(List<Category> categories) {
        return categories.stream().map(this::convertToTreeVo).collect(Collectors.toList());
    }

    private CategoryTreeVo convertToTreeVo(Category category) {
        CategoryTreeVo vo = new CategoryTreeVo();
        vo.setId(category.getId());
        vo.setName(category.getName());
        vo.setImage(category.getImage());
        List<Category> children = categoryService.getChildren(category.getId());
        if (!children.isEmpty()) {
            vo.setChildren(convertToTreeVO(children));
        }
        return vo;
    }
}
